package com.example.springbootsecurity.config;

import com.example.springbootsecurity.service.CustomUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.NoOpPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

/**
 * @author ljw
 * @description
 * @date 2022/8/17 7:58
 */
@Configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    // SpringSecurity 的密码加密工具 org.springframework.security.crypto.factory.PasswordEncoderFactories#createDelegatingPasswordEncoder
    //Spring Security5.0版本及之后的默认密码的编码方式BCryptPasswordEncoder,而不再是NoOpPasswordEncoder
    @Bean
    PasswordEncoder passwordEncoder(){
        //明文密码
        return NoOpPasswordEncoder.getInstance();
        //使用 bcypt 做密码加密
//        return new BCryptPasswordEncoder();
    }



    @Autowired
    private CustomUserService customUserService;

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(customUserService);
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .antMatchers("/bootstrap-3.4.1/**", "/login").permitAll() //无需认证的为static下的静态资源，以及/index请求
                .anyRequest().authenticated() //所有请求需要登录认证后才能访问
                .and()
                .formLogin()
                    .loginPage("/login")
                    .failureUrl("/login?error")
                    .permitAll() //定制登录行为，登录页面可任意访问
                .and()
                .logout().permitAll(); //定制注销行为，注销请求可以任意访问
    }
}
